/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ie.tcd.cs.railtickets.commons.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 *
 * @Created on 15-Apr-2009, 17:28:21
 * @author Wenbo Sun
 */
public class FileUtil {


    public static void makeDir(String path, String name) throws Exception {
        File parent = new File(path);
        if(!parent.exists())
            throw new Exception("path is not existed");
        if(!parent.isDirectory()){
            throw new Exception("path is not a dir");
        }
        File dir = new File(parent.getPath() + "/" + name);
        if(dir.exists())
            throw new Exception("dir is existed");
        dir.mkdir();
    }

    public static boolean isExisted(File file) {
        if (file.exists())
            return true;
        return false;
    }

    public static boolean isExisted(String path) {
        File file = new File(path);
        return isExisted(file);
    }

    public static boolean isFolderAndExisted(File file) {
        if (isExisted(file)){
            if (file.isDirectory())
                return true;
        }
        return false;
    }

    public static boolean isFolderAndExisted(String path) {
        File file = new File(path);
        return isFolderAndExisted(file);
    }

    public static boolean saveObject(File file, Object object) throws FileNotFoundException, IOException {
        FileOutputStream fos = new FileOutputStream(file);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(object);
        fos.flush();
        fos.close();
        return true;
    }

    public static boolean saveObject(String path, Object object) throws FileNotFoundException, IOException {
        File file = new File(path);
        saveObject(file, object);
        return true;
    }

    public static Object file2Object(File file) throws FileNotFoundException, IOException, ClassNotFoundException {
        FileInputStream fis = new FileInputStream(file);
        ObjectInputStream ois = new ObjectInputStream(fis);
        Object object = ois.readObject();
        fis.close();
        return object;
    }

    public static Object file2Object(String path) throws FileNotFoundException, IOException, ClassNotFoundException {
        File file = new File(path);
        return file2Object(file);
    }
}
